<template>
  <view class="page-container">
    <!-- 筛选工具栏 -->
    <view class="filter-bar">
      <view class="filter-group">
        <text class="total-count">共{{ filteredTasks.length }}条</text>
        <view class="select-group">
          <!-- 状态选择 -->
          <picker 
            class="status-select"
            mode="selector" 
            :range="statusOptions"
            range-key="label"
            @change="handleStatusChange"
          >
            <view class="select-box">
              <text>{{ selectedStatus.label }}</text>
              <uni-icons type="arrowdown" size="14" color="#666" />
            </view>
          </picker>

          <!-- 方式选择 -->
          <picker
            class="method-select"
            mode="selector"
            :range="methodOptions"
            range-key="label"
            @change="handleMethodChange"
          >
            <view class="select-box">
              <text>{{ selectedMethod.label }}</text>
              <uni-icons type="arrowdown" size="14" color="#666" />
            </view>
          </picker>
        </view>
      </view>

      <!-- 日期范围选择 -->
      <view class="date-range-group">
        <picker
          mode="date"
          class="date-picker"
          :value="startDate"
          @change="handleStartDateChange"
        >
          <view class="date-input">
            <uni-icons type="calendar" size="16" color="#007AFF" />
            <text>{{ startDate }}</text>
          </view>
        </picker>
        <text class="date-separator">—</text>
        <picker
          mode="date"
          class="date-picker"
          :value="endDate"
          @change="handleEndDateChange"
        >
          <view class="date-input">
            <uni-icons type="calendar" size="16" color="#007AFF" />
            <text>{{ endDate }}</text>
          </view>
        </picker>
      </view>
    </view>

    <!-- 任务卡片列表 -->
    <scroll-view class="task-list" scroll-y>
      <view 
        v-for="task in sortedTasks" 
        :key="task.repairId" 
        class="task-card"
        :class="{ 'urgent': isUrgent(task.appointmentDate) }"
      >
        <!-- 紧急标识 -->
        <view v-if="isUrgent(task.appointmentDate, task.status)" class="urgent-mark">
          <uni-icons type="alert" size="14" color="#FFF" />
          <text>即将到期</text>
        </view>

        <!-- 卡片内容 -->
        <view class="card-content">
          <!-- 左侧信息区 -->
          <view class="info-section">
            <view class="info-row">
              <text class="label">维修单号：</text>
              <text class="order-number">{{ task.repairNumber }}</text>
            </view>
            <view class="info-row">
              <text class="label">服务方式：</text>
              <text class="method-tag" :class="task.repairMethod">
                {{ repairMethodLabels[task.repairMethod] }}
              </text>
            </view>
            <view class="info-row">
              <text class="label">预约时间：</text>
              <text class="time-text">{{ formatTime(task.appointmentDate) }}</text>
            </view>
          </view>

          <!-- 右侧状态区 -->
          <view class="status-section">
            <view class="status-group">
              <view class="status-badge" :class="task.status">
                {{ statusLabels[task.status] }}
              </view>
              <button 
                class="detail-btn"
                hover-class="btn-hover"
                @click="viewDetail(task.repairId)"
              >
                查看详情
                <uni-icons type="forward" size="14" color="#007AFF" />
              </button>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { dayjs } from '@/uni_modules/iRainna-dayjs/js_sdk/dayjs.min.js'
import { getToken } from '@/utils/auth.js'  // 引入获取 token 的方法

// 模拟数据
const tasks = ref([])

// 常量映射
const statusLabels = {
  1: '进行中',
  2: '已完成'
}

const repairMethodLabels = {
  1: '到店维修',
  2: '上门取车'
}

// 筛选选项配置
const statusOptions = ref([
  { label: '全部状态', value: 'all' },
  { label: '进行中', value: 1 },
  { label: '已完成', value: 2 }
])

const methodOptions = ref([
  { label: '全部方式', value: 'all' },
  { label: '到店维修', value: 1 },
  { label: '上门取车', value: 2 }
])

// 筛选状态
const selectedStatus = ref(statusOptions.value[0])
const selectedMethod = ref(methodOptions.value[0])
const startDate = ref(dayjs().format('YYYY-MM-DD'))
const endDate = ref(dayjs().add(7, 'day').format('YYYY-MM-DD'))

// 计算属性
const filteredTasks = computed(() => {
  return tasks.value.filter(task => {
    const statusMatch = selectedStatus.value.value === 'all' || task.status === selectedStatus.value.value
    const methodMatch = selectedMethod.value.value === 'all' || task.repairMethod === selectedMethod.value.value
    const start = dayjs(startDate.value).startOf('day').valueOf()
    const end = dayjs(endDate.value).endOf('day').valueOf()
    const taskTime = dayjs(task.appointmentDate).valueOf()
    return statusMatch && methodMatch && (taskTime >= start && taskTime <= end)
  })
})

// 排序任务
const sortedTasks = computed(() => {
  return [...filteredTasks.value].sort((a, b) => {
    const aUrgent = isUrgent(a.appointmentDate)
    const bUrgent = isUrgent(b.appointmentDate)
    if (aUrgent !== bUrgent) return aUrgent ? -1 : 1
    if (a.status !== b.status) return a.status === 1 ? -1 : 1
    return a.appointmentDate - b.appointmentDate
  })
})

// 事件处理
const handleStatusChange = (e) => {
  const index = e.detail.value
  selectedStatus.value = statusOptions.value[index]
}

const handleMethodChange = (e) => {
  const index = e.detail.value
  selectedMethod.value = methodOptions.value[index]
}

const handleStartDateChange = (e) => {
  startDate.value = e.detail.value
}

const handleEndDateChange = (e) => {
  endDate.value = e.detail.value
}

// 请求维修记录
const fetchRepairRecords = (userId, pageNo = 1, pageSize = 7) => {
  const token = getToken()  // 获取 token
  
  uni.request({
    url: `http://localhost:8866/sn/repairRecords/getRepairRecords/${userId}`,
    method: 'GET',
    data: {
      pageNo,
      pageSize
    },
    header: {
      'Authorization': token  // 添加 Authorization header
    },
    success: (res) => {
		console.log(res)
      if (res.statusCode === 200) {
        tasks.value = res.data.data.records || []  // 将返回的数据赋值给 tasks
		
      } else {
        uni.showToast({
          title: '获取维修记录失败',
          icon: 'none'
        })
      }
    },
    fail: (err) => {
      uni.showToast({
        title: '请求失败',
        icon: 'none'
      })
    }
  })
}

// 在页面加载时获取数据
fetchRepairRecords(1)  // 传入用户 ID

// 实用方法
const formatTime = (timestamp) => dayjs(timestamp).format('MM/DD HH:mm')

const isUrgent = (timestamp, status) => {
  if (status === 2) return false
  const now = Date.now()
  const taskTime = dayjs(timestamp).valueOf()
  const twentyFourHours = 24 * 60 * 60 * 1000
  return taskTime > now && taskTime < (now + twentyFourHours)
}

// 剩余时间计算
const remainingHours = (timestamp) => {
  const now = Date.now()
  const diff = dayjs(timestamp).valueOf() - now
  return Math.ceil(diff / (60 * 60 * 1000))
}

const viewDetail = (id) => {
	console.log(id)
  uni.navigateTo({ url: `/pages/work/maintenance_task/maintenance_details/maintenance_details?repairId=${id}` })
}
</script>


<style lang="scss" scoped>
.page-container {
  background: #f8f9fa;
  min-height: 100vh;
}

/* 筛选栏样式 */
.filter-bar {
  background: #fff;
  padding: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

  .filter-group {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24rpx;
  }

  .total-count {
    font-size: 28rpx;
    color: #666;
  }

  .select-group {
    display: flex;
    gap: 20rpx;
  }

  .select-box {
    display: flex;
    align-items: center;
    padding: 12rpx 24rpx;
    background: #f5f5f5;
    border-radius: 8rpx;
    font-size: 28rpx;
    color: #333;
  }

  .date-range-group {
    display: flex;
    align-items: center;
    gap: 16rpx;

    .date-picker {
      flex: 1;
    }

    .date-input {
      display: flex;
      align-items: center;
      gap: 8rpx;
      padding: 16rpx;
      background: #f5f5f5;
      border-radius: 8rpx;
      font-size: 28rpx;
      color: #333;
    }

    .date-separator {
      color: #999;
      font-size: 28rpx;
    }
  }
}

/* 任务卡片样式 */
.task-list {
  padding: 24rpx;
}

.task-card {
  position: relative;
  background: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

  &.urgent {
    border-left: 6rpx solid #ff9f0a;
    background: linear-gradient(to right, #fff9f0 0%, #ffffff 20%);
  }

  .urgent-mark {
    position: absolute;
    top: 1rpx;
    left: -8rpx;
    background: #ffaa00;
    border-radius: 32rpx 0 0 32rpx;
    padding: 3rpx 10rpx 3rpx 12rpx;
    display: flex;
    align-items: center;
    gap: 8rpx;
    font-size: 20rpx;
    color: #fff;
    box-shadow: 0 2rpx 8rpx rgba(255, 159, 10, 0.2);

    &::after {
      content: '';
      position: absolute;
      right: -8rpx;
      top: 0;
      width: 8rpx;
      height: 100%;
      background: inherit;
      clip-path: polygon(0 0, 100% 50%, 0 100%);
    }
  }
}

.card-content {
  display: flex;
  justify-content: space-between;
}

.info-section {
  flex: 1;
  padding-right: 24rpx;

  .info-row {
    display: flex;
    align-items: baseline;
    margin-bottom: 20rpx;

    &:last-child {
      margin-bottom: 0;
    }

    .label {
      font-size: 28rpx;
      color: #666;
      min-width: 140rpx;
    }

    .order-number {
      font-size: 32rpx;
      font-weight: 500;
      color: #333;
    }

    .method-tag {
      display: inline-block;
      padding: 4rpx 16rpx;
      border-radius: 6rpx;
      font-size: 28rpx;

      &.shop {
        background: #e8f4ff;
        color: #007AFF;
      }

      &.pickup {
        background: #f0f4ff;
        color: #5856D6;
      }
    }

    .time-text {
      font-size: 28rpx;
      color: #333;
    }
  }
}

.status-section {
  width: 200rpx;
  display: flex;
  flex-direction: column;
  align-items: flex-end;

  .status-group {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    gap: 16rpx;
  }

  .status-badge {
    display: inline-block;
    padding: 8rpx 20rpx;
    border-radius: 32rpx;
    font-size: 24rpx;
    line-height: 1.2;

    &.processing {
      background: #fff4e5;
      color: #ff9500;
    }

    &.completed {
      background: #e6f4ea;
      color: #34c759;
    }
  }

  .detail-btn {
    padding: 12rpx 24rpx;
    background: #f5f5f5;
    font-size: 28rpx;
    color: #007AFF;
    display: inline-flex;
    align-items: center;
    gap: 8rpx;
    transition: all 0.2s;
    line-height: 1;

    &.btn-hover {
      opacity: 0.8;
      transform: scale(0.95);
    }
  }
}
</style>